package thread_try;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

public class AtomicTest {

    private static AtomicInteger atomicInteger = new AtomicInteger();
    private static AtomicLong atomicLong = new AtomicLong();
    private static Integer integer = 0;
    private static Long lon = 0L;
    private static LongAdder longAdder = new LongAdder();

    public static void main(String[] args) {
        // 创建10个线程，分别对atomicInteger、atomicLong、integer、lon进行1000次增加1的操作
        // 如果操作是原子性的，那么正确结果 = 10 * 1000 = 10000
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    atomicInteger.incrementAndGet();
                    atomicLong.incrementAndGet();
                    lon++;
                    integer++;
                    longAdder.increment();
                }
            });
        }

        // 启动线程
        for (Thread thread : threads) {
            thread.start();
        }

        // 保证10个线程运行完成
        try {
            for (Thread thread : threads) {
                thread.join();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("AtomicInteger的结果：" + atomicInteger);
        System.out.println("AtomicLong的结果：" + atomicLong);
        System.out.println("Integer的结果：" + integer);
        System.out.println("Long的结果：" + lon);
        System.out.println("longAdder的结果: "+longAdder);
    }
}
